package com.pfzy.lib.net.interceptor;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.pfzy.lib.net.utils.AesUtil;
import com.pfzy.lib.net.utils.RsaUtil;
import com.pfzy.lib.sdk.log.UXLog;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class ResponseInterceptor implements Interceptor {
    private String TAG = "RequestDataInterceptor";
    private String decryptKey = null;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        String responseSign = response.header("Sign");
        ResponseBody responseBody = response.body();
        int responseCode = response.code();
        UXLog.v(TAG, "返回 code: " + responseCode);
        UXLog.v(TAG, "返回 sign: " + responseSign);
        UXLog.v(TAG, "返回 data: " + responseBody);

        if (responseBody == null) return response;
        MediaType mediaType = responseBody.contentType();

        switch (responseCode) {
            case 200: {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE);
                Buffer buffer = source.buffer();
                Charset charset = StandardCharsets.UTF_8;
                if (charset != null) {
                    // 服务器返回结果 可处理加解密或者token失效
                    String bodyString = buffer.clone().readString(charset);
                    Gson gson = new Gson();
                    HashMap<String, Object> map = new HashMap<>();
                    map = gson.fromJson(bodyString, map.getClass());
                    UXLog.d(TAG, "返回数据: " + map.toString());

//                        Object retCode = map.get("ret");
                    Object code = map.get("code");
                    Object data = map.get("data");
                    Object message = map.get("message");

                    if (code instanceof String && data instanceof String) {
                        if (code.equals("0000") && ((String) data).length() > 0) {
                            try {
                                String signStruk = RsaUtil.decryptByPrivateKey(responseSign, decryptKey);
                                HashMap<String, Object> signMap = new HashMap<>();
                                signMap = gson.fromJson(signStruk, signMap.getClass());
                                Object aeskey = signMap.get("aesKey");
                                if (aeskey instanceof String) {
                                    String dataStr = AesUtil.aes256ECBPkcs7PaddingDecrypt((String) data, (String) aeskey);
                                    JsonObject jsonData = new JsonParser().parse(dataStr).getAsJsonObject();
                                    map.put("data", jsonData);

                                    Gson gsonData = new GsonBuilder().disableHtmlEscaping().create();
                                    String base = gsonData.toJson(map);
                                    UXLog.d("输出", base);

                                    ResponseBody newRespBody = ResponseBody.create(mediaType, base);
                                    response = response.newBuilder().body(newRespBody).build();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                break;
            }
            case 400:
            case 403:
            case 404:
            case 500:
            case 503:
            case 504: {
                response = response.newBuilder().code(responseCode).message("连接服务器失败，请稍后再试").build();
                break;
            }
            default:
                break;
        }
        return response;
    }

    public void setDecryptKey(String key) {
        decryptKey = key;
    }
}
